// pages/login/login.js
const app = getApp()
const lvToast = require("../../utils/toastAndloading")
Page({
  data: {
    primaryColor: app.primaryColor, // 主题色
    loadingBtn: false, // 登录按钮loading
    phone: '', // 手机号
    code: '', // 验证码
    codeSeconds: 60, // 倒计时时间
    codeTimer: null, // 倒计时定时器
    codeDisabled: false, // 发送验证码的禁用
    codeBtnText: '获取验证码', // 验证码文字
    targetTimer: null, // 跳转的定时器
  },
  onLoad(options) {

  },
  onShow() {

  },
  onUnload() {
    if (this.data.codeTimer) clearInterval(this.data.codeTimer)
    if (this.data.targetTimer) clearTimeout(this.data.targetTimer)
  },
  // 手机号输入框
  onPhoneInput(e){
    const value = e.detail.value.replace(/\D/g,'').slice(0,11)
    this.setData({ phone: value })
  },
  // 验证码输入框
  onCodeInput(e){
    const value = e.detail.value.replace(/\D/g,'').slice(0,6)
    this.setData({ code: value })
  },
  // 获取验证码
  getCode(){
    const { checkPhone } = app.util
    if (!checkPhone(this.data.phone)){
      wx.showToast({ title:'请输入正确的手机号', icon:'none' })
      return
    }
    if (this.data.codeDisabled) return
    lvToast.showLoading()
    app.api.user.getSmsCode({phone: this.data.phone}).then(res => {
      // console.log(res)
      lvToast.hideLoading()
      if (res.code == 200) {
        lvToast.showToast('验证码发送成功，5分钟内有效')
        this.startCountDown()
      } else {
        lvToast.showToast(res.msg || '验证码发送失败，请重试')
      }
    })
  },
  // 开始倒计时
  startCountDown(){
    this.setData({ codeDisabled: true, codeSeconds: 60, codeBtnText: '60秒后重试' })
    const timer = setInterval(()=>{
      let { codeSeconds } = this.data
      codeSeconds--
      if (codeSeconds <= 0){
        clearInterval(timer)
        this.setData({ codeDisabled: false, codeTimer: null, codeBtnText: '获取验证码' })
      } else {
        this.setData({ codeSeconds, codeBtnText: `${codeSeconds}秒后重试` })
      }
    },1000)
    this.setData({ codeTimer: timer })
  },
  // 登录
  onLogin(){
    const { checkPhone, is_numeric } = app.util
    if (!checkPhone(this.data.phone)){
      wx.showToast({ title:'请输入正确的手机号', icon:'none' })
      return
    }
    if (!this.data.code || !is_numeric(this.data.code)){
      wx.showToast({ title:'请输入正确的验证码', icon:'none' })
      return
    }
    this.setData({ loadingBtn: true })
    // 调用登录接口，成功后存储并跳转首页
    app.api.user.userLogin({
      phone: this.data.phone,
      smsCode: this.data.code
    }).then(res => {
      this.setData({ loadingBtn: false })
      if (res.code == 200) {
        lvToast.showSuccess('登录成功')
        app.globalData.loginStatus = true
        wx.setStorageSync('token', res.data.token)
        wx.setStorageSync('userInfo', res.data)
        this.data.targetTimer = setTimeout(()=> {
          wx.redirectTo({
            url: '/pages/index/index',
            complete: ()=> { clearTimeout(this.data.targetTimer) }
          })
        }, 1000)
      } else {
        lvToast.showToast(res.msg || '登录失败')
      }
    })

  }
})